
import { _decorator, Component, game, JsonAsset, Prefab, resources, instantiate, Node, find, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('main')
export class main extends Component {
    private static instance: main;

    public static getInstance() {
        return this.instance;
    }
    @property(JsonAsset)
    public configJson: JsonAsset = null;


    public static ui: Node = null;
    public static loading: Node = null;
    public jsonData: object


    public static roleList: string[] = [];
    onLoad() {
        main.instance = this;

        game.addPersistRootNode(this.node);
        this.jsonData = this.configJson.json;
        main.ui = find("Canvas/UI");
        main.loading = find("Canvas/loading");
        const promise = this.getModuleNode(this.jsonData["default"]);
        promise.then((res) => {
            res.setParent(main.ui);
        }).catch((res) => {
            console.log(res);
        });
    }

    /**
     * 通过名字获取模块的预制体 并 instantiate后的Node 返回的是个 promise
     * @param moduleName 
     * @returns Promise<Node>
     */
    async getModuleNode(moduleName: string): Promise<Node> {
        return new Promise<Node>((resolve, reject) => {
            this.jsonData["Modules"].forEach((value: string) => {
                if (value === moduleName) {
                    resources.load(moduleName + "/index", Prefab, (err, data) => {
                        if (err) {
                            reject("模块不存在");
                        }
                        let prefabNode: Node = instantiate(data);
                        if (prefabNode) {
                            resolve(prefabNode);
                        }
                    });
                }
            });
        });
    }
    /**
     * 加载公共资源
     */
    async loadPublicResources(path: string): Promise<Node> {
        return new Promise<Node>((resolve, reject) => {
            resources.load("Public/" + path, Prefab, (err, data) => {
                if (err) {
                    reject("模块不存在");
                }
                let prefabNode: Node = instantiate(data);
                if (prefabNode) {
                    resolve(prefabNode);
                }
            });

        });
    }

    onLoading() {
        main.loading.active = true;
    }
    offLoading() {
        main.loading.active = false;
    }
    /**
     * 记载场景
     */
    loadScene(SceneName: string) {
        director.loadScene(SceneName, this.loadSceneEnd)
    }
    loadSceneEnd() {
        main.ui = find("Canvas/UI");
        main.loading = find("Canvas/loading");
    }
}

